package com.fowo.api.service.handleWork;

import cn.hutool.extra.spring.SpringUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.fowo.api.datainterface.util.RestUtilLingXing;
import com.fowo.api.datainterface.util.lingxing.LingXingApiSign;
import com.fowo.api.entity.*;
import com.fowo.api.model.purchase.order.PurchaseOrderPullPurchaseOrderAction;
import com.fowo.api.model.purchase.order.PurchaseOrderVo;
import com.fowo.api.model.purchase.order.product.PurchaseOrderProductItemVo;
import com.fowo.api.service.handleWork.jindieEntity.addrssInfo;
import com.fowo.api.service.handleWork.jindieEntity.lXPurchaseOrder;
import com.fowo.api.service.impl.*;
import com.fowo.api.sys.entity.SysFile;
import com.fowo.api.sys.entity.SysUser;
import com.fowo.api.sys.service.impl.SysUserServiceImpl;
import com.fowo.api.user.model.JwtUserInfo;
import com.fowo.api.util.LocalDateUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.ibatis.reflection.MetaObject;
import org.apache.ibatis.reflection.SystemMetaObject;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@Slf4j
@Component
public class purchaseOrderPullPurchaseOrderAction implements PurchaseOrderPullPurchaseOrderAction {
    //拉取领星数据
    public final static String path2 = "https://openapi.lingxing.com";
    public final static String appId = "ak_s4t9uVnYKwknd";
    public final static String appSecret = "xZHRMyjrRAfJkvVCoVWcxQ==";
    @Resource
    private StockInServiceImpl stockInService;
    @Resource
    protected StockInProductServiceImpl stockInProductService;
    @Resource
    private PurchaseOrderServiceImpl purchaseOrderService;
    @Resource
    private SysUserServiceImpl userService;
    @Resource
    private ProductServiceImpl productService;
    @Resource
    private SupplierServiceImpl supplierServiceImpl;
    @Resource
    private WarehouseServiceImpl warehouseService;
    @Resource
    private ShopInfoServiceImpl shopInfoService;
    @Resource
    private ListingFatherServiceImpl ListingFatherService;
    @Resource
    private RestUtilLingXing restUtilLingXing;

    @Resource
    protected PurchaseOrderProductServiceImpl purchaseOrderProductService;


    @Transactional(rollbackFor = Exception.class)
    @Override
    public void run() throws Exception {
        RedissonClient redissonClient = SpringUtil.getBean(RedissonClient.class);
        RLock lock = redissonClient.getLock("serial_new2");
        Assert.isTrue(!lock.isLocked(),"正在同步数据");
        new Thread(new Runnable() {
            @Override
            public void run() {
                String todayNow = LocalDateUtils.getTodayNow();
                try {
                   Boolean tryLock = lock.tryLock(1,1800,TimeUnit.SECONDS);
                   Assert.isTrue(tryLock,"正在同步数据");
                    String format = LocalDateUtils.format(new Date(), LocalDateUtils.DATE_PATTERN);
                    Date date = LocalDateUtils.addDateDays(new Date(), -1);
                    String format1 = LocalDateUtils.format(date, LocalDateUtils.DATE_PATTERN);
                    getAttributeList(null, format1, format);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                   Assert.isTrue(false,"正在同步数据");
                } catch (Exception e) {
                    e.printStackTrace();
                   log.error("采购订单拉取:"+todayNow,e.getLocalizedMessage());
               } finally {
                   if(lock.isLocked()){
                       lock.unlock();
                   }
                }
            }
        }).start();

    }

    private MetaObject getMetaObject() {
        Map<String, Object> queryParam = new HashMap<>();
        queryParam.put("appId", appId);
        queryParam.put("appSecret", appSecret);
        String url = path2 + "/api/auth-server/oauth/access-token";
        RestTemplate REST_TEMPLATE = new RestTemplate();
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        HttpEntity<String> httpEntity = new HttpEntity<>("", headers);
        String s = populateQueryParams(queryParam, url, false);
        ResponseEntity<Object> objectResponseEntity = REST_TEMPLATE.postForEntity(s, httpEntity, Object.class);
        return SystemMetaObject.forObject(objectResponseEntity.getBody());
    }

    public void run2(JSONObject orderSn) throws Exception {

        if (orderSn == null) {
            return;
        }
//        JSONObject jsonObject = JSONObject.parseObject(orderSn);
        getAttributeList(orderSn.getString("orderSn"), null, null);
    }

    public void run3(JSONObject orderSn) throws Exception {
        if (orderSn == null) {
            return;
        }
        RedissonClient redissonClient = SpringUtil.getBean(RedissonClient.class);
        RLock lock = redissonClient.getLock("serial_new2");
        Assert.isTrue(!lock.isLocked(),"正在同步数据");
        new Thread(new Runnable() {
            @Override
            public void run() {
                String todayNow = LocalDateUtils.getTodayNow();
                try {
                    Boolean tryLock = lock.tryLock(1,1800,TimeUnit.SECONDS);
                    Assert.isTrue(tryLock,"正在同步数据");
                    getAttributeList(null, orderSn.getString("start_date"), orderSn.getString("end_date"));
                } catch (InterruptedException e) {
                    e.printStackTrace();
                    Assert.isTrue(false,"正在同步数据");
                } catch (Exception e) {
                    log.error("采购订单拉取:"+todayNow,e.getLocalizedMessage());
                } finally {
                    if(lock.isLocked()){
                        lock.unlock();
                    }
                }
            }
        }).start();
    }

     synchronized void getAttributeList(String orderSn, String start_date, String end_date) throws Exception {
        // 定义分页参数
        Integer offset = 0;
        Integer length = 500;
        lXPurchaseOrder purchaseOrder = getPurchaseOrder(offset, length, orderSn, start_date, end_date);
        Integer total = purchaseOrder.getTotal();
        if (total > length) {
            int pageNum = total / length;
            if (total % length != 0) {
                pageNum = pageNum + 1;
            }
            for (int i = 1; i < pageNum; i++) {
                offset = offset + length;
                getPurchaseOrder(offset, length, orderSn, start_date, end_date);
            }
        }
    }

    private lXPurchaseOrder getPurchaseOrder(Integer offset, Integer length, String orderSn, String start_date, String end_date) throws Exception {
        MetaObject MetaObject = getMetaObject();
        Map<String, Object> queryParam = new HashMap<>();
        queryParam.put("timestamp", System.currentTimeMillis() / 1000 + "");
        queryParam.put("access_token", MetaObject.getValue("data.access_token").toString());
        queryParam.put("app_key", appId);
        queryParam.put("offset", offset);
        queryParam.put("length", length);
        queryParam.put("search_field_time", "create_time");//入库时间
        if (start_date != null && end_date != null) {
            queryParam.put("start_date", start_date);
            queryParam.put("end_date", end_date);
        }
        queryParam.put("status", 1);
        if (orderSn != null) {
            List<String> str = new ArrayList<String>();
            if (orderSn.contains(",")) {
                str = Arrays.asList(orderSn.split(","));
            } else {
                str.add(orderSn);
            }
            if (str.size() > 0) {
                queryParam.put("order_sn", str);
            }
        }

        String sign = LingXingApiSign.signBatch(queryParam, appId);
        queryParam.put("sign", sign);
        RestTemplate REST_TEMPLATE = new RestTemplate();
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        HttpHeaders requestHeaders = new HttpHeaders();
        requestHeaders.setContentType(MediaType.APPLICATION_JSON);
        HttpEntity<Map<String, Object>> requestEntity = new HttpEntity<>(queryParam, requestHeaders);
        String s = populateQueryParams(queryParam, addrssInfo.path + addrssInfo.getPurchaseOrders, false);
        String s2 = REST_TEMPLATE.postForObject(s, requestEntity, String.class);
        lXPurchaseOrder purchaseOrder = JSON.parseObject(s2, lXPurchaseOrder.class);
        Assert.isTrue(purchaseOrder.getCode().intValue() == 0, "请求领星接口失败:" + s2);
        regainLingXingData(purchaseOrder, offset, length, orderSn, start_date, end_date);
        //转换成并存库
        handlePurchaseOrder(purchaseOrder);
        return purchaseOrder;
    }

    private void handlePurchaseOrder(lXPurchaseOrder purchaseOrder) throws Exception {
        if(purchaseOrder.getData().size()==0){
            return;
        }
        Set<String> collect = purchaseOrder.getData().stream().map(lXPurchaseOrder.DataDTO::getOptRealname).collect(Collectors.toSet());
        Set<String> collect1 = purchaseOrder.getData().stream().map(lXPurchaseOrder.DataDTO::getSupplierName).collect(Collectors.toSet());
        Set<String> collect4 = purchaseOrder.getData().stream().map(lXPurchaseOrder.DataDTO::getWareHouseName).collect(Collectors.toSet());

        Set<Set<String>> collect6 = purchaseOrder.getData().stream().map(x -> x.getItemList().stream().map(lXPurchaseOrder.DataDTO.ItemListDTO::getSku).collect(Collectors.toSet())).collect(Collectors.toSet());
        Set<String>collect7=new HashSet<>();
        collect6.stream().forEach(x->collect7.addAll(x));

        Set<Set<Long>> collect8 = purchaseOrder.getData().stream().map(x -> x.getItemList().stream().map(lXPurchaseOrder.DataDTO.ItemListDTO::getSid).collect(Collectors.toSet())).collect(Collectors.toSet());
        Set<Long>collect9=new HashSet<>();
        collect8.stream().forEach(x->collect9.addAll(x));

        Set<Set<String>> collect10 = purchaseOrder.getData().stream().map(x -> x.getItemList().stream().filter(z -> z.getFnsku() != null && !z.getFnsku().equals("")).map(lXPurchaseOrder.DataDTO.ItemListDTO::getFnsku).collect(Collectors.toSet())).collect(Collectors.toSet());
        Set<String>collect11=new HashSet<>();
        collect10.stream().forEach(x->collect11.addAll(x));

        //查询所有的人员信息
        QueryWrapper<SysUser> queryWrapper=new QueryWrapper();
        queryWrapper.select("id,name");
        queryWrapper.in("name",collect);
        List<SysUser> list = userService.list(queryWrapper);

        //查询供应商
        QueryWrapper<Supplier> queryWrapper1=new QueryWrapper();
        queryWrapper1.select("id,supplier_name");
        queryWrapper1.in("supplier_name",collect1);
        List<Supplier> list1 = supplierServiceImpl.list(queryWrapper1);
//        if(true){
//            return;
//        }
        //查询仓库的
        QueryWrapper<Warehouse> queryWrapper2=new QueryWrapper();
        queryWrapper2.select("id,name");
        queryWrapper2.in("name",collect4);
        List<Warehouse> list2 = warehouseService.list(queryWrapper2);

        //查询所有的产品信息
        QueryWrapper<Product> queryWrapper3=new QueryWrapper();
        queryWrapper3.select("id,sku,pic_url");
        queryWrapper3.in("sku",collect7);
        List<Product> list3 = productService.list(queryWrapper3);

        //查询店铺信息 collect9
        QueryWrapper<ShopInfo> queryWrapper4=new QueryWrapper();
        queryWrapper4.select("id,shop_code");
        queryWrapper4.in("shop_code",collect9);
        List<ShopInfo> list4 = shopInfoService.list(queryWrapper4);

//      ShopInfo one = shopInfoService.getOne(Wrappers.<ShopInfo>query().lambda().eq(ShopInfo::getShopCode, itemListDTO.getSid()));
        //查询listing 数据
        QueryWrapper<ListingFather> queryWrapper5=new QueryWrapper();
        queryWrapper5.select("id,sku,sid,fnsku");
//        queryWrapper5.in("sku",collect7);
        queryWrapper5.in("sid",collect9);
        if(collect11.size()>0){
            queryWrapper5.in("fnsku",collect11);
        }
        List<ListingFather> list5 = ListingFatherService.list(queryWrapper5);
//        List<ListingFather> list = ListingFatherService.list(Wrappers.<ListingFather>query().lambda()
//                .eq(ListingFather::getFnsku, itemListDTO.getFnsku())
//                .eq(ListingFather::getSku, itemListDTO.getSku())
//                .eq(ListingFather::getSid, itemListDTO.getSid()));


        for (int i = 0; i < purchaseOrder.getData().size(); i++) {
            lXPurchaseOrder.DataDTO dataDTO = purchaseOrder.getData().get(i);
            //判断是否新增过了
            long count = purchaseOrderService.count(Wrappers.<PurchaseOrder>query().lambda().eq(PurchaseOrder::getPurchaseOrderCode, dataDTO.getOrderSn()));

            PurchaseOrderVo model = new PurchaseOrderVo();
            model.setPurchaseOrderCode(dataDTO.getOrderSn());
//            SysUser one4 = userService.getOne(Wrappers.<SysUser>query().lambda().eq(SysUser::getName, dataDTO.getOptRealname()));
            List<SysUser> collect2 = list.stream().filter(x -> x.getName().equals(dataDTO.getOptRealname())).collect(Collectors.toList());
            if (collect2.size()>0) {
                model.setOptUid(collect2.get(0).getId());
            }
            model.setSupplierName(dataDTO.getSupplierName());
            model.setSupplierCode(dataDTO.getSupplierId() != null ? dataDTO.getSupplierId().toString() : null);
//            Supplier one = supplierServiceImpl.getOne(Wrappers.<Supplier>query().lambda().eq(Supplier::getSupplierName, dataDTO.getSupplierName()));
            List<Supplier> collect3 = list1.stream().filter(x -> x.getSupplierName().equals(dataDTO.getSupplierName())).collect(Collectors.toList());
            model.setSupplierId(collect3.size()>0 ? collect3.get(0).getId() : null);
            //仓库
            if (dataDTO.getWareHouseName() != null) {
//                Warehouse one2 = warehouseService.getOne(Wrappers.<Warehouse>query().lambda().eq(Warehouse::getName, dataDTO.getWareHouseName()));
                List<Warehouse> collect5 = list2.stream().filter(x -> x.getName().equals(dataDTO.getWareHouseName())).collect(Collectors.toList());
                Assert.isTrue(collect5.size()>0, dataDTO.getWareHouseName() + ",仓库不存");
                model.setWarehouseName(collect5.get(0).getName());
                model.setWid(collect5.get(0) != null ? collect5.get(0).getId() : null);
            }

            model.setPurSear(dataDTO.getOptRealname());//purSear//采购员
//            SysUser one3 = userService.getOne(Wrappers.<SysUser>query().lambda().eq(SysUser::getName, dataDTO.getOptRealname()));
            List<SysUser> collect5 = list.stream().filter(x -> x.getName().equals(dataDTO.getOptRealname())).collect(Collectors.toList());
            model.setOptUid(collect5.size()>0 ? collect5.get(0).getId() : null);
            model.setContactPerson(dataDTO.getContactPerson());
            model.setContactNumber(dataDTO.getContactNumber());
            model.setAnStatus("1");
            model.setArrivalStatus("0");//未到货
            model.setSettlementMethod("JS01");//现结
            model.setProductType("1");
            model.setFeePartType("0");
            model.setInspectionType("0");
            model.setIncludingTax("0");//到货量
            model.setPayStatus(dataDTO.getPayStatus() != null ? dataDTO.getPayStatus().toString() : null);
            model.setRemarks(dataDTO.getRemark());
            model.setQuantityReceived(dataDTO.getQuantityEntry());//到货量
            JwtUserInfo currentUser = JwtUserInfo.fromHeader();
            model.setCreateTime(new Date());
            model.setLastUpdateTime(new Date());
            if (currentUser != null) {
                model.setCreateUser(currentUser.getUserId());
                model.setLastUpdateUser(currentUser.getUserId());
            }
            model.setPurchaseQuantity(dataDTO.getQuantityReal() != null ? dataDTO.getQuantityReal().toString() : null);
            addPurchaseOrderItem(dataDTO.getItemList(), model,list3,list4,list5);
            if (count >0) {
               // updatePicUrl(one1, dataDTO.getItemList());
            } else {
                purchaseOrderService.create(model);
            }
        }
    }

    private void addPurchaseOrderItem(List<lXPurchaseOrder.DataDTO.ItemListDTO> itemList, PurchaseOrderVo model, List<Product> productList, List<ShopInfo> shopInfoList,List<ListingFather> list5) {
        List<PurchaseOrderProductItemVo> purchaseOrder = new ArrayList<>();
        if (itemList != null && itemList.size() > 0) {
            for (int i = 0; i < itemList.size(); i++) {
                lXPurchaseOrder.DataDTO.ItemListDTO itemListDTO = itemList.get(i);
                PurchaseOrderProductItemVo purchaseOrderProduct = new PurchaseOrderProductItemVo();
                purchaseOrderProduct.setSku(itemListDTO.getSku());
                purchaseOrderProduct.setProductName(itemListDTO.getProductName());
//                Product product = productService.getOne(Wrappers.<Product>query().lambda().eq(Product::getSku, itemListDTO.getSku()));
                List<Product> collect = productList.stream().filter(x -> x.getSku().equals(itemListDTO.getSku())).collect(Collectors.toList());
                Assert.isTrue(collect.size()>0, itemListDTO.getSku() + ",SKU不存在");
                Product product = collect.get(0);
                purchaseOrderProduct.setProductId(product != null ? product.getId() : null);
                purchaseOrderProduct.setPicUrl(product != null ? product.getPicUrl() : null);
                purchaseOrderProduct.setPlanSn(itemListDTO.getPlanSn());
                //purchaseOrderProduct.setMsku(itemListDTO.getMsku());
                if (itemListDTO.getSid() != null && !(itemListDTO.getSid().intValue() == 0)) {
                    List<ShopInfo> collect1 = shopInfoList.stream().filter(x -> Long.valueOf(x.getShopCode()).longValue() == itemListDTO.getSid().longValue()).collect(Collectors.toList());
//                    ShopInfo one = shopInfoService.getOne(Wrappers.<ShopInfo>query().lambda().eq(ShopInfo::getShopCode, itemListDTO.getSid()));
                    Assert.isTrue(collect1.size()>0, "店铺不存在" + itemListDTO.getSid());
                    ShopInfo one = collect1.get(0);
                    purchaseOrderProduct.setSid(one != null ? one.getId() : null);
                    purchaseOrderProduct.setScode(itemListDTO.getSid() != null ? itemListDTO.getSid().toString() : null);
                }
                //查listing 的 fnsku
                purchaseOrderProduct.setFnskuFnsku(itemListDTO.getFnsku());
                if (itemListDTO.getSid() != null && itemListDTO.getFnsku() != null && !itemListDTO.getFnsku().equals("")) {
//                    List<ListingFather> list = ListingFatherService.list(Wrappers.<ListingFather>query().lambda()
//                            .eq(ListingFather::getFnsku, itemListDTO.getFnsku())
//                            .eq(ListingFather::getSku, itemListDTO.getSku())
//                            .eq(ListingFather::getSid, itemListDTO.getSid()));
                    List<ListingFather> list = list5.stream().filter(x -> Long.valueOf(x.getSid()).longValue() == itemListDTO.getSid().longValue()
//                            && x.getSku().equals(itemListDTO.getSku())
                            && x.getFnsku().equals(itemListDTO.getFnsku())).collect(Collectors.toList());
                    Assert.isTrue(list.size() > 0, itemListDTO.getFnsku() + "不存在");
                    purchaseOrderProduct.setFnsku(list.size() > 0 ? list.get(0).getId() : null);
                    purchaseOrderProduct.setLxFnsku(itemListDTO.getFnsku());
                    purchaseOrderProduct.setFnskuFnsku(itemListDTO.getFnsku());
                }
                String localInventory = purchaseOrderService.getLocalInventory(itemListDTO.getSid(), purchaseOrderProduct.getProductId(), purchaseOrderProduct.getFnsku());
                String fbaInventory = purchaseOrderService.getFbaInventory(itemListDTO.getSid(), purchaseOrderProduct.getProductId(), itemListDTO.getFnsku());
                String skuSales = purchaseOrderService.getSale(itemListDTO.getSid(), purchaseOrderProduct.getProductId(), purchaseOrderProduct.getFnsku());
                purchaseOrderProduct.setLocalDayList(localInventory);
                purchaseOrderProduct.setFbaDayList(fbaInventory);
                purchaseOrderProduct.setSkuSales(skuSales);
                purchaseOrderProduct.setApplicationNum(itemListDTO.getQuantityReal());
                purchaseOrderProduct.setQuantityReceived(itemListDTO.getQuantityEntry()!=null?itemListDTO.getQuantityEntry().intValue():0);
                purchaseOrderProduct.setQuantityReturn(0);
                purchaseOrderProduct.setQuantityReceive(itemListDTO.getQuantityReceive().intValue());
                purchaseOrderProduct.setExpectArriveTime(StringUtils.isNotBlank(itemListDTO.getExpectArriveTime()) ? LocalDateUtils.toDate(itemListDTO.getExpectArriveTime(), LocalDateUtils.DATE_PATTERN) : null);
                purchaseOrderProduct.setLxPrice(new BigDecimal(itemListDTO.getPrice()));
                purchaseOrderProduct.setLxTotalPrice(new BigDecimal(itemListDTO.getAmount()));
                purchaseOrderProduct.setRemarks(itemListDTO.getRemark());
                JwtUserInfo currentUser = JwtUserInfo.fromHeader();
                purchaseOrderProduct.setCreateTime(new Date());
                purchaseOrderProduct.setLastUpdateTime(new Date());
                if (currentUser != null) {
                    purchaseOrderProduct.setCreateUser(currentUser.getUserId());
                    purchaseOrderProduct.setLastUpdateUser(currentUser.getUserId());
                }
                purchaseOrder.add(purchaseOrderProduct);
            }
        }
        model.setPurchaseOrde(purchaseOrder);
    }


    static String populateQueryParams(Map<String, Object> request, String purl, boolean isEncode) {
        if (request.isEmpty()) {
            return purl;
        }
        StringBuilder url = new StringBuilder(purl);
        url.append("?");
        for (Map.Entry<String, Object> entry : request.entrySet()) {
            try {
                if (isEncode) {
                    url.append(URLEncoder.encode(entry.getKey(), "UTF-8")).append("=").append(URLEncoder.encode(String.valueOf(entry.getValue()), "UTF-8"));
                } else {
                    url.append(entry.getKey()).append("=").append(entry.getValue());
                }
                url.append("&");
            } catch (UnsupportedEncodingException e) {
            }
        }
        if (url.charAt(url.length() - 1) == '&') {
            url.deleteCharAt(url.length() - 1);
        }
        return url.toString();
    }

    /**
     * 循环获取领星数据直到成功
     *
     * @return
     */
    private lXPurchaseOrder regainLingXingData(lXPurchaseOrder purchaseOrder, Integer offset, Integer length, String orderSn, String start_date, String end_date) throws Exception {
        while (purchaseOrder.getCode() != 0) {
            Object inventoryListResultObj = new JSONObject();
            Integer code = purchaseOrder.getCode();
//				ip不在白名单，appId不存在，appSecret不正确，请求的api未授权，请求的api未授权，接口签名不正确，
            if (code == 3001002 || code == 2001001 || code == 2001002 || code == 2001004 || code == 2001006 || code == 3001001) {
                cn.hutool.core.lang.Assert.isTrue(false, "查询订单列表失败，原因：" + purchaseOrder.getMessage());
                purchaseOrder = new lXPurchaseOrder();
                break;
            }
            if (code == 3001008 || code == 2001005) {
                try {
                    Thread.sleep(5000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            getPurchaseOrder(offset, length, orderSn, start_date, end_date);

        }
        return purchaseOrder;
    }


    private void updatePicUrl(PurchaseOrder order, List<lXPurchaseOrder.DataDTO.ItemListDTO> itemList) {
        LambdaQueryWrapper<PurchaseOrderProduct> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(PurchaseOrderProduct::getPurchaseOrderId, order.getId());
        List<PurchaseOrderProduct> purchaseOrderProducts = purchaseOrderProductService.list(wrapper);
        if (CollectionUtils.isEmpty(purchaseOrderProducts)) {
            return;
        }
        List<String> skuList = itemList.stream().map(lXPurchaseOrder.DataDTO.ItemListDTO::getSku).collect(Collectors.toList());
        if (CollectionUtils.isEmpty(skuList)) {
            return;
        }
        LambdaQueryWrapper<Product> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.in(Product::getSku, skuList);
        List<Product> productList = productService.list(queryWrapper);
        if (CollectionUtils.isEmpty(productList)) {
            return;
        }
        Map<String, List<SysFile>> skuMap = productList.stream().filter(e->CollectionUtils.isNotEmpty(e.getPicUrl())).collect(Collectors.toMap(Product::getSku, Product::getPicUrl));

        purchaseOrderProducts.stream().forEach(item -> {
            if (!skuMap.containsKey(item.getSku())) {
                return;
            }
            item.setPicUrl(skuMap.get(item.getSku()));
        });

        purchaseOrderProductService.updateBatchById(purchaseOrderProducts);
    }
}
